﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using  Acando.Dynamics.CRM.Silverlight.Library.CrmSdk;
using Acando.Dynamics.CRM.Silverlight.Library.MetaSdk;
using  Acando.Dynamics.CRM.Silverlight.Library.Controls.FieldControls;

namespace Acando.Dynamics.CRM.Silverlight.Library.Converter
{
    public class CrmPicklistConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return null;
            else if (targetType == typeof(String))
            {
                String s;
                if (((Picklist)value).name != null)
                    s = ((Picklist)value).name.ToString();
                else
                    s = "<<empty>>";
                return s;
            }
            else if (value is Picklist && targetType == typeof(object) && (DropdownType)parameter == DropdownType.Picklist)
                return ((Picklist)value).Value;
            else if (value is Status && targetType == typeof(object) && (DropdownType)parameter == DropdownType.StatusReason)
                return ((Status)value).Value;
            else
                throw new NotSupportedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return null;
            else if (targetType == typeof(Picklist) && value is Option)
            {
                Picklist pl = new Picklist();
                pl.name =((Option) value).Label.UserLocLabel.Label;
                pl.Value = ((Option)value).Value.Value;
                return pl;
            }
            else if (targetType == typeof(Picklist) && value is int)
            {
                Picklist pl = new Picklist();
                pl.Value = (int)value;
                return pl;
            }
            else if (targetType == typeof(Status) && value is int)
            {
                Status s = new Status();
                s.Value = (int)value;
                return s;
            }                                  
            else
                throw new NotSupportedException(targetType.ToString());
        }

        #endregion
    }
}
